import {createRouter,  createWebHistory, RouteRecordRaw} from 'vue-router'
import {createVNode,     render} from "vue";

import Login from "@/views/auth/Login.vue";
import Register from "@/views/auth/Register.vue";
import LoadingBar from "@/components/LoadingBar.vue";
import Auth from "@/views/auth/Auth.vue";
import useUserStore from "@/store/user";
import useMenuStore from "@/store/menu";
import {Menu} from "@/interface/menu";
import Root from "@/views/Root.vue";
import Dashboard from "@/views/home/Dashboard.vue";


const routes: Array<RouteRecordRaw> = [
  {
    path: "/auth/",
    // name: "Auth",
    component: Auth,
    redirect: "/auth/login",
    children: [
      {
        path: "login",
        name: "登录",
        component: Login,
        meta: {
          title: "登录",
          transition: "animate__fadeIn",
        },
      },
      {
        path: "register",
        name: "注册",
        component: Register,
        meta: {
          title: "注册",
          transition: "animate__bounceIn",
        },
      }
    ]
  },
  {
    path: "/",
    name: "Root",
    component: Root,
    redirect: {
      path: '/dashboard'
    },
    children: [
      {
        path: '/dashboard',
        name: '首页',
        component: Dashboard,
        meta: {
          // title: '首页',
          transition: 'animate__bounceIn',
          closable: false, //标签可关闭
        }
      }
    ]
  }

];

//***********Vite 的组件懒加载***************
//获取文件夹及其嵌套的多级子文件夹的 .vue 文件夹，注意 ** 是关键。
//一个 *：匹配当前目录下的文件；
//两个 *：匹配当前目录及其嵌套的全部子目录下的文件；
const viteComponent = import.meta.glob("../views/**/*.vue")

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  scrollBehavior: (to, from, savedPosition) => {//滚动行为
    if (savedPosition) {
      return savedPosition
    } else {
      return {
        top: 0
      }
    }
  },
  routes
})


//进度条：虚拟dom
const vNode = createVNode(LoadingBar)
render(vNode, document.body)

const whitelist = ['/auth/login', '/auth/register']

let registerRouteFresh = true // 定义标识，记录路由是否添加

const userStore = useUserStore
const menuStore = useMenuStore

//路由前置守卫
router.beforeEach(async (to, from, next) => {
  // document.title = to.meta.title as string
  console.log('浏览器header:', to.name)
  document.title = to.name as string

  //进度条
  vNode.component?.exposed?.startLoading()

  if (whitelist.includes(to.path) || userStore().isLogin) {
    if(userStore().isLogin){//1.登录
      if(menuStore().list.length===0){
        await menuStore().get()
      }
      if(registerRouteFresh){//1.1 未加载动态路由
        let d1 = Array<RouteRecordRaw>()
        await generateRoutes(menuStore().list).then(res => {
           d1 = res
          //添加404页面
          d1.push({
              path: '/:error*', // /:error -> 匹配 /, /one, /one/two, /one/two/three, 等
              // name: '404',
              component: () => import('@/views/error/404.vue'),
              meta: {
                title: '404',
                transition: 'animate__bounceIn',
                closable: true
              }
            })
         })

        d1.forEach((r) => {
          router.addRoute('Root', r)
        })
        registerRouteFresh = false
        next({ ...to, replace: true })
      }else{ //1.2 已加载动态路由
        next()
      }
    }else{
      next()
    }
  } else {//2.未登录
    next('/auth/login')
  }

})

//路由后置守卫
router.afterEach((to, from, next) => {
  //进度条
  vNode.component?.exposed?.endLoading()
})

const  generateRoutes = async (menus: Menu[]) => {
  let routes: Array<RouteRecordRaw> = []

  routes = menus.map( (r) => {
    let route =  <RouteRecordRaw>{
      path: r.path,
      name: r.name,
      meta: {
        title: r.name,
        transition: r.transition,
        icon: r.icon,
      },
      component: viteComponent[`../views/${r.component}.vue`],
    }


    if (!!r.children && r.children.length > 0) {
       generateRoutes(r.children).then(res => {
         route.children = res
      })
    }

    return route
  })

  return routes
}

export default router